package web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/*****************************************************
First servlet: Process the data in server.
1. Finds the good information pass the isNameNull, yourFuture, name to the another server.
2. Forwards that to another servlet called AnotherSvl
*****************************************************/
public class HoroscopeServlet extends HttpServlet{
	
	//1. Prepare the variables
	
	String isNameNull= "false";
	String[] future = {"You will have a long life",
				"You will have a rich life",
				"You will find a tall handsome stranger",
				"You will have six children"};
	String  yourFuture;
	int  ZodiacSign=0;
	
	//2. Override service method
	public void service (HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
			//2.1 Retrieve values from the req
			String name = req.getParameter("name");
			String sex = req.getParameter("sex");
			String horoscope = req.getParameter("Zodiac");
			
			//2.2 Config necessary part--No longer need in LAB4
			//res.setContentType("text/html");
			//PrintWriter out = res.getWriter();
			
			//2.3 Preprocess the zodiac data (Data processed by the server)
			ZodiacSign = Integer.parseInt(horoscope);
			
			//2.4 Logic operation
			if(name.equals("")){
				isNameNull = "true";
			}
			
			if(sex.equals("Male") && ZodiacSign<=6)
			yourFuture = future[0];
			else if(sex.equals("Male") && ZodiacSign>6)
			yourFuture = future[1];
			else if(sex.equals("female") && ZodiacSign<=6)
			yourFuture = future[2];
			else if(sex.equals("female") && ZodiacSign>6)
			yourFuture = future[3];
			
			//3. Attach and Pass the information to another Server
			req.setAttribute("name",name);
			req.setAttribute("future", yourFuture);
			req.setAttribute("isNameNull",isNameNull);
			
			RequestDispatcher view = req.getRequestDispatcher("/Horoscope2");
			view.forward(req, res);
			
			//4.Generate HTML code
			
//			out.println("<html><head>");
//			out.println("<srcipt type=\"text/javascript\">");
//			out.println("function genFuture()" );
//			out.println("");
//			out.println("</srcipt>");
//			out.println("<body>");
			
//			// ErrorCase: NullPointer
//			if(isNameNull){
//				out.println("Please identify yourself " +
//				"(by indicating your name), "+ 
//				"so that your horoscope can be " +
//				"given!</body></html>");
//				return;
//			}
//			
//			out.println("<p> Hello, "+ name + "</p>");
//			out.println("<p>" + yourFuture + "</p>");
//			out.println("</body></html>");
//			out.close();
		}
}